package com.alibaba.cloud.tech.service.impl;

import com.alibaba.cloud.tech.dao.TechSheetMapper;
import com.alibaba.cloud.tech.entity.TechSheet;
import com.alibaba.cloud.tech.service.TechSheetService;
import com.alibaba.framework.utils.UUIDUtil;
import com.alibaba.framework.wrapper.RedisWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
public class TechSheetServiceImpl implements TechSheetService {

    private static final Logger LOGGER = LoggerFactory.getLogger(TechSheetServiceImpl.class);

    @Autowired
    private TechSheetMapper techSheetMapper;

    @Autowired
    private RedisWrapper<String, Object> redisWrapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int add(TechSheet techSheet) {

        String orderId = techSheet.getOrderId();
        boolean bool = preventDuplicateConsumption(orderId);
        if (bool) {
//            throw new RuntimeException(orderId + " => 处方已申请!");
            LOGGER.info("{} =>处方已申请", orderId);
        }

        techSheet.setId(UUIDUtil.uuid());
        techSheet.setCreateTime(new Date());
        int i = techSheetMapper.insert(techSheet);

        redisWrapper.putValueWithExpireTime(orderId, techSheet.getOrderName(), 600L, TimeUnit.SECONDS);
        if (i<0) {
            throw new RuntimeException("新增检验检查申请失败!");
        }
        return i;
    }

    /**
     * @descript 防重校验
     * @author focus
     * @date 2025/10/24
     */
    private boolean preventDuplicateConsumption(String orderId) {

        return redisWrapper.hasKey(orderId);
    }
}
